<?php

namespace Mall\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;
use Util\ModelUtils;

class OrderModel extends BaseModel
{
    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
        ['create_ip', 'get_client_ip', self::MODEL_INSERT, 'function'],

    ];

    protected $_validate = [
    ];

    protected $_scope = [
        'valid' => [
            'where' => ['is_hide' => 0, 'status' => ['neq', 'cancel']],
        ],
    ];

    public function changePaid(array $orderIds, $transaction_id)
    {
        if (empty($orderIds)) return false;
        D('Order')
            ->where(['status' => 'unpaid', 'order_id' => ['in', $orderIds]])
            ->setField([
                'status' => 'paid',
                'paid_time' => time(),
                'transaction_id' => $transaction_id,
            ]);
        /* 增加销量，时机可能会改变 */
        $soldDict = D('OrderGoods')->where(['order_id' => ['in', $orderIds]])->getField('goods_id,quantity', true);
        foreach ($soldDict as $goodsId => $quantity) {
            D('Goods')->where(['goods_id' => $goodsId])->setInc('sold_num', $quantity);
        }
    }

    public function changeExpressNo($orderId, $expressNo)
    {
        D('Order')->where(['order_id' => $orderId])->setField([
            'express_no' => $expressNo,
            'delivered_time'
        ]);
    }


    public function calcTotalPrice($shop, $goodsList)
    {
        $user = get_user();
        $skus = array_column($goodsList, 'sku');
        $dbskus = D('GoodsSku')->where(['name' => ['in', $skus]])->getField('name,stock,price,wholesale_price', true);
        $total = 0;
        /*注意该系统并没有结算价*/
        // $settlementTotal = 0;
        foreach ($goodsList as $goods) {
            $price = $user['role'] === '2' ? $dbskus[$goods['sku']]['wholesale_price'] : $dbskus[$goods['sku']]['price'];
            $total += $price * $goods['quantity'];
            // $settlementTotal += $goods['settlement_price'] * $goods['quantity'];
        }
        $total += $shop['express_fee'];
        return $total;
    }

    public function setReceiveAddress($orderId, $receiveAddress)
    {
        $orderAddr = D('OrderAddr')->getByOrderId($orderId);
        if ($orderAddr) {
            D('OrderAddr')->where(['order_id' => $orderId])->setField(
                array_keep($receiveAddress, ['name', 'mobile', 'province', 'city', 'district', 'detail']));
        } else {
            D('OrderAddr')->add(array_merge(
                array_keep($receiveAddress, ['name', 'mobile', 'province', 'city', 'district', 'detail']), 
                ['order_id' => $orderId]
            ));

        }
    }

    public function getOrders($orderIds)
    {
        $orders = D('Order')->where(['order_id' =>['in',$orderIds]])->select();
        ModelUtils::hasMany($orders, ['relation' => 'OrderGoods', 'refKey' => 'order_id', 'foreignKey' => 'order_id', 'name' => 'items']);
        ModelUtils::hasOne($orders, ['relation' => 'OrderAddr', 'refKey' => 'order_id', 'foreignKey' => 'order_id', 'name' => 'receive_addr']);
        ModelUtils::hasOne($orders, ['relation' => 'Shop', 'refKey' => 'shop_id', 'foreignKey' => 'shop_id']);
        return $orders;

    }

    public  function putOutStock($sku, $quantity)
    {
        
    }

    public function _after_find(&$record,$option)
    {

    }

    public function _after_select(&$records,$option)
    {
        
    }
    
}
